package com.chang.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.chang.order.service.OrderService;
import com.chang.order.vo.PayAsyncVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: changzhenxi
 * @date: 2025年03月28日 10:36
 * @Version: 1.0
 * @description:
 */
@Slf4j
@RestController
public class OrderPayedListener {

    @Value("${alipay.alipay-public-key}")
    private String alipayPublicKey;

    @Resource
    OrderService orderService;

    @PostMapping("alipay/notify")
    public String handleAliPayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws AlipayApiException {
        // 只要收到了支付宝的异步回调通知，告诉我们支付成功，就直接按照文档上返回success，支付宝就不会再频繁间隔通知了
        // Map<String, String[]> parameterMap = request.getParameterMap();

        // 验证签名 成功之后再进行后续操作
        Map<String, String> params = convertRequestParamsToMap(request);
        boolean signVerified = AlipaySignature.rsaCheckV1(
                params,
                alipayPublicKey,
                "UTF-8",
                "RSA2"
        );

        if (signVerified) {
            String tradeStatus = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                // 处理支付成功逻辑（更新订单状态）
                log.info("已接收到支付宝的异步回调通知,签名验证成功.....");
                String result = orderService.handlePayResult(payAsyncVo);
                log.info("订单状态修改成功");
                return result;
            } else System.out.println("签名验证失败");
        }
        return "failure";
    }

    private Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        return params;
    }
}
